/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ortus.daemon;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author jphipps
 */
public class cronDaemon extends Thread {
	private List<cronItem> crontab = new ArrayList<cronItem>();
	private Thread_pool pool;
	private boolean stopcron = false;

	private Object crontab_lock = new Object();

	public cronDaemon() {
		pool = new Thread_pool(10,10);
		ortus.api.DebugLog(ortus.ortusvars.INFO, "cronDaemon: Loading");
	}
	
	public void run() {
		ortus.api.DebugLog(ortus.ortusvars.INFO, "cronDaemon: Running");
		while( true) {
			try {
				if ( stopcron)
					break;
				for ( cronItem ci : crontab) {
					if ( ci.IsNeedToBeRun() ) {
//					   ortus.api.DebugLog(ortus.ortusvars.TRACE2,"cronServer: running: " + ci.GetCmd()[0]);
					   pool.execute(new ortus.daemon.daemonProcess(ci.GetCmd()));
					   ci.SetJustRun();
					}
				}
				Thread.sleep(1000);
			} catch (InterruptedException ex) {
				ortus.api.DebugLog(ortus.ortusvars.ERROR, "cron: sleep exception: " + ex);
			}
		}
		ortus.api.DebugLog(ortus.ortusvars.INFO,"cronDaemon: Stopping");
	}

	public void Shutdown() {
		stopcron = true;
	}

	public void AddCron(long run_interval, String run_method, Object[] run_parms) {
		synchronized(crontab_lock) {
		    crontab.add(new cronItem(run_interval,run_method,run_parms));
		}
		ortus.api.DebugLog(ortus.ortusvars.TRACE2,"AddCron: Just added: " + run_method + " interval: " + run_interval);
	}

	public void RemoveCron(long run_interval, String run_method, Object[] run_parms) {
//		ortus.api.DebugLog(ortus.ortusvars.INFO, "RemoveCron: removing: interval: " + run_interval + " method: " + run_method);
		cronItem rci = new cronItem(run_interval, run_method, run_parms);
//		ortus.api.DebugLog(ortus.ortusvars.TRACE2, " removing object: " + rci.toString());
		for( int x = 0 ; x < crontab.size(); x++) {
//		    ortus.api.DebugLog(ortus.ortusvars.TRACE2, "Checking: " + ((cronItem)crontab.get(x)).toString());
		    if ( ((cronItem)crontab.get(x)).toString().equals(rci.toString())) {
			    synchronized(crontab_lock) {
				    crontab.remove(x);
				    ortus.api.DebugLog(ortus.ortusvars.TRACE2,"RemoveCron: Just removed: " + run_method);
			    }
		    }
		}
		
	}
}
